package com.ww.ll.search;

import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.apache.lucene.queryparser.flexible.standard.QueryParserUtil;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import com.ww.ll.LuceneBase;

public class DocSearcher extends LuceneBase {
	public static final int MAX_RESULT = 100;
	
	public void searchKeyword(String kwQuery) throws IOException, QueryNodeException{
		Query query = QueryParserUtil.parse(new String[]{kwQuery}
			, new String[]{FIELD_NAME_CONTENT}
			, getAnalyzer());
		
		IndexSearcher is = new IndexSearcher(DirectoryReader.open(getIndexDir()));
		TopDocs topDocs = is.search(query, MAX_RESULT);
		
		System.err.println("Doc count: " + topDocs.scoreDocs.length);
		
		for(ScoreDoc sdoc : topDocs.scoreDocs){
			Document doc = is.doc(sdoc.doc);
			System.out.println(doc.get(FIELD_NAME_FS_PATH));
			System.out.println(doc.get(FIELD_NAME_FS_NAME));
			System.out.println("===============================");
		}
	}
	
	public static void main(String[] args) throws IOException, QueryNodeException {
		DocSearcher s = new DocSearcher();
		/*		String[] result = 
				s.split(s.getAnalyzer(), "都是先从容易的做起");
						//, IOUtils.toString(new FileReader("E:\\project\\eclipse_ws\\luceneLearn\\conf\\doc\\doc.txt")));
		
		System.out.println(Arrays.toString(result));*/
		
		
		s.searchKeyword("北京");
	}
}
